package com.controller;

import com.entity.Notice;
import com.service.INoticeService;
import com.vo.noticeVo.AddNoticeVo;
import com.vo.noticeVo.NoticeListRequestVo;
import com.vo.noticeVo.UpdateNoticeVo;
import com.vo.productVo.addProductVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Describe 公告管理控制器
 */
@Controller
@RequestMapping("/notice")
public class NoticeController {
    @Resource
    INoticeService noticeService;

    @Resource
    HttpServletRequest request;

    /**
     * 获取公告列表
     */
    @RequestMapping("/getNoticeList")
    @ResponseBody
    public List<Notice> getNoticeList(NoticeListRequestVo vo){
        Object session= request.getSession().getAttribute("user");
        if(session != null) {
            noticeService.getNoticeList(vo);
        }
        return null;
    }

    /**
     * 添加公告
     */
    @PostMapping("/addNotice")
    @ResponseBody
    public String addNotice(AddNoticeVo addVo, MultipartFile file) throws IOException {
        Object session= request.getSession().getAttribute("user");
        if(session !=null) {
            String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
            File dirs = new File("src/main/resources/static/images/notice/" + filename);
            if (file.isEmpty()) {
                noticeService.addNotice(addVo);
                return "图片上传失败！";
            } else {
                file.transferTo(new File(dirs.getAbsolutePath()));
                addVo.setImage("/static/images/notice/" + filename);
                noticeService.addNotice(addVo);
                return "添加成功!";
            }
        }
        return null;
    }

    /**
     *修改公告
     */
    @PutMapping("/updateNotice")
    @ResponseBody
    public void updateNotice(UpdateNoticeVo vo){
        Object session= request.getSession().getAttribute("user");
        if(session != null) {
            noticeService.updateNotice(vo);
        }
    }

    /**
     * 删除公告
     */
    @DeleteMapping("/deleteNotice")
    @ResponseBody
    public void deleteNotice(Integer id){
        Object session= request.getSession().getAttribute("user");
        if(session != null) {
            noticeService.deleteNotice(id);
        }
    }
}
